package com.huluobo.a2206parkdemo.patrol

import android.app.AlertDialog
import android.app.TimePickerDialog
import android.app.TimePickerDialog.OnTimeSetListener
import android.content.DialogInterface
import android.content.DialogInterface.OnClickListener
import android.util.Log
import android.view.LayoutInflater
import android.widget.EditText
import android.widget.TimePicker
import androidx.lifecycle.MutableLiveData
import androidx.recyclerview.widget.GridLayoutManager
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.Gson
import com.huluobo.a2206parkdemo.R
import com.huluobo.a2206parkdemo.adapter.PointAdapter
import com.huluobo.a2206parkdemo.databinding.ActivityAddPatrolBinding
import com.huluobo.base.bean.PPointBean
import com.huluobo.base.bean.PPointBeanItem
import com.huluobo.base.mvvm.BaseActivity
import com.huluobo.base.net.Const
import com.tencent.smtt.utils.m
import dagger.hilt.android.AndroidEntryPoint
import okhttp3.MediaType
import okhttp3.MediaType.Companion.parse
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import java.lang.StringBuilder
import java.util.Calendar

@AndroidEntryPoint
class AddPatrolActivity : BaseActivity<ActivityAddPatrolBinding, PatrolViewModel>() {
    private var startTime = 0L
    private var endTime = 0L
    private var time = 0L
    private lateinit var pointAdapter: PointAdapter

    private val calendar = Calendar.getInstance().apply {
        set(Calendar.HOUR, 0)
        set(Calendar.MINUTE, 0)
        set(Calendar.SECOND, 0)
        set(Calendar.MILLISECOND, 0)
    }

    override fun initData() {
        vm.getAllPoint()
        vm.getAllPointSuccess.observe(this) {
            val list = Gson().fromJson(it, PPointBean::class.java)
            pointAdapter.data.clear()
            pointAdapter.data.addAll(list)
            pointAdapter.notifyDataSetChanged()
        }

        vm.addPointSuccess.observe(this) {
            ToastUtils.showLong("添加巡逻点成功")
            vm.getAllPoint()
        }

        vm.addPatrolSuccess.observe(this) {
            ToastUtils.showLong("添加成功")
            finish()
        }
    }

    override fun initView() {
        binding.addPatrolHeader.headerTitle.text = "添加巡更路线"
        binding.addPatrolHeader.headerBack.setOnClickListener { finish() }

        binding.addPatrolStartTimeIv.setOnClickListener {
            TimePickerDialog(
                this,
                object : OnTimeSetListener {
                    override fun onTimeSet(view: TimePicker?, hourOfDay: Int, minute: Int) {
                        calendar.set(Calendar.HOUR_OF_DAY, hourOfDay)//把选中的时间转换为当前时间的毫秒
                        calendar.set(Calendar.MINUTE, minute)//把选中的时间转为为当前时间的毫秒
                        startTime = calendar.timeInMillis//将选中的毫秒级时间给开始时间赋值
                        binding.addPatrolStartTimeNowTv.text = "$hourOfDay:$minute"
                    }
                },
                calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), true
            ).show()
        }

        binding.addPatrolEndTimeIv.setOnClickListener {
            TimePickerDialog(
                this,
                object : OnTimeSetListener {
                    override fun onTimeSet(view: TimePicker?, hourOfDay: Int, minute: Int) {
                        calendar.set(Calendar.HOUR_OF_DAY, hourOfDay)//把选中的时间转换为当前时间的毫秒
                        calendar.set(Calendar.MINUTE, minute)//把选中的时间转为为当前时间的毫秒
                        endTime = calendar.timeInMillis//将选中的毫秒级时间给结束时间赋值
                        binding.addPatrolEndTimeNowTv.text = "$hourOfDay:$minute"
                        time = endTime - startTime
                        if (time <= 0 || startTime == 0L) {
                            ToastUtils.showLong("请重新选择时间")
                        } else {
                            val newTime = time / 1000 / 60 / 60
                            binding.addPatrolTimeNowTv.text = "${newTime}小时"
                        }
                    }
                },
                calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), true
            ).show()
        }

        binding.addPatrolRv.layoutManager = GridLayoutManager(this, 2)
        pointAdapter = PointAdapter()
        binding.addPatrolRv.adapter = pointAdapter
        val newPointList = mutableListOf<PPointBeanItem>()
        val pointListLiveData = MutableLiveData<List<PPointBeanItem>>()

        pointAdapter.setOnItemClickListener { adapter, view, position ->
            val pointBeanItem = pointAdapter.data[position]
            newPointList.add(pointBeanItem)
            pointListLiveData.postValue(newPointList)
        }

        pointListLiveData.observe(this) {
            val points = StringBuilder()
            newPointList.forEach {
                points.append(it.pointName)
                points.append(",")
            }
            binding.addPatrolChoicePointResultTv.text = points.toString()
        }

        binding.addPatrolAddPointBtn.setOnClickListener {
            val view = LayoutInflater.from(this).inflate(R.layout.dialog_add_point, null)
            AlertDialog.Builder(this)
                .setView(view)
                .setNegativeButton("取消", null)
                .setPositiveButton("确定", object : OnClickListener {
                    override fun onClick(dialog: DialogInterface?, which: Int) {
                        val edittext = view.findViewById<EditText>(R.id.dialog_add_point_name_tv)
                        if (edittext.text.toString().isNotEmpty()) {
                            val pointName = edittext.text.toString()
                            val map = mutableMapOf<String, String>()
                            map[Const.PARAM_POINT_NAME] = pointName
                            val json = Gson().toJson(map)
                            val body = RequestBody.create(Const.MEDIA_TYPE.toMediaTypeOrNull(), json)
                            vm.addPoint(body)
                        }
                    }
                })
                .show()
        }

        binding.addPatrolCommitBtn.setOnClickListener {
            val pStart = binding.addPatrolStartTimeNowTv.text.toString()
            val pEnd = binding.addPatrolEndTimeNowTv.text.toString()
            val pTime = binding.addPatrolTimeNowTv.text.toString()
            //巡逻点位展示的时候是个json转换来的,所以上传的时候需要转化为一个json再上传
            val pPoint = Gson().toJson(newPointList)
            Log.i("TagA", "pPoint:$pPoint")

            if (pStart.isNotEmpty() && pEnd.isNotEmpty() && pTime.isNotEmpty() && pPoint.isNotEmpty()) {
                val map = mutableMapOf<String, Any>()
                map[Const.PARAM_P_START] = pStart
                map[Const.PARAM_P_END] = pEnd
                map[Const.PARAM_P_TIME] = pTime
                map[Const.PARAM_P_GROUP_ID] = 49
                map[Const.PARAM_P_POINT] = pPoint

                val json = Gson().toJson(map)
                val body = RequestBody.create(Const.MEDIA_TYPE.toMediaTypeOrNull(), json)
                vm.addPatrol(body)
            }
        }
    }
}